<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools show-before>
        <template #before>
          <span>共{{ page.total }}条记录</span>
        </template>
        <template #after>
          <el-button
            type="success"
            @click="$router.push('/import')"
          >excel导入</el-button>
          <el-button type="danger" @click="exportData">excel导出</el-button>
          <!-- v-if="$store.state.user.userInfo.roles.points.includes('add-employee')" -->
          <el-button
            v-if="checkPermission('add-employee')"
            type="primary"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </page-tools>
      <!-- 表单组件 -->
      <el-card>
        <!-- v-loading element ui 自定义的指令,原理: 添加绝对定位的盒子,挡住内容 -->
        <el-table v-loading="Loading" border :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="头像" width="120px">
            <template v-slot="{ row }">
              <img
                v-imgerror="require('@/assets/common/bigUserHeader.png')"
                style="
                  border-radius: 50%;
                  width: 100px;
                  height: 100px;
                  padding: 10px;
                "
                :src="row.staffPhoto"
                @click="showQrCodedialog(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <!-- 方式2 -- 通过 element ui 的格式化的属性( formatter )来完成  -->
          <el-table-column
            label="聘用形式"
            sortable=""
            :formatter="formatterHireType"
          >
            <!-- 方式1 -- 使用局部过滤器时,再用prop获取数据就无法完成需求,所以这里直接使用插槽 -->
            <!-- <template v-slot="{row}">
              {{ row.formOfEmployment | hireType }}
            </template> -->
          </el-table-column>
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template v-slot="{ row }">{{
              row.timeOfEntry | formatDate
            }}</template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template v-slot="{ row }">
              <el-switch :value="row.enableState" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="onAssignRole(row.id)">角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="onDelEmployee(row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :current-page.sync="page.page"
            :page-size="page.size"
            :total="page.total"
            layout="prev, pager, next"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
    </div>
    <add-employee :show-dialog.sync="showDialog" />

    <!-- 二维码弹出层 -->
    <el-dialog
      title="二维码"
      :visible.sync="qrCodedialogVisible"
      width="30%"
    >
      <el-row type="flex" justify="center" align="middle">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>

    <!-- 分配角色弹出层 -->
    <assign-role ref="assignRole" :user-id="userId" :show-roledialog.sync="showRoledialog" />
  </div>
</template>

<script>
import { delEmployeeById, getEmployeeList } from '@/api/employees'
import EmployeesEnum from '@/api/constant/employees.js'
import AddEmployee from './components/add-employee.vue'
import { formatDate } from '@/filters'
// 导入生成二维码依赖
import QRCode from 'qrcode'
import AssignRole from './components/assign-role.vue'
export default {
  name: 'EmployeesIndex',
  components: { AddEmployee, AssignRole },
  // 格式化列内容 --- 方式1 --- 通过过滤器
  // 全局过滤器
  // Vue.filters('',{})
  // 局部过滤器
  // filters: {
  //   hireType(value) {
  //     const f = EmployeesEnum.hireType.find(t => t.id === value)
  //     return f ? f.value : '未知'
  //   }
  // },
  props: {},
  data() {
    return {
      list: [],
      page: {
        page: 1,
        size: 10,
        total: 0
      },
      Loading: false,
      showDialog: false,
      qrCodedialogVisible: false,
      showRoledialog: false,
      userId: ''
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getEmployeeList()
  },
  mounted() {},
  methods: {
    async getEmployeeList() {
      this.Loading = true
      const { rows, total } = await getEmployeeList(this.page)
      this.list = rows
      this.page.total = total
      this.Loading = false
    },
    handleCurrentChange(val) {
      this.page.page = val
      this.getEmployeeList()
    },
    formatterHireType(row, column, cellValue, index) {
      const f = EmployeesEnum.hireType.find(t => t.id === row.formOfEmployment)
      return f ? f.value : '未知'
    },
    onDelEmployee(row) {
      console.log(row)
      // 通过elmecon
      this.$confirm('确认删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async action => {
        await delEmployeeById(row.id)
        this.getEmployeeList()
        // 通过elme
        this.$message({
          message: '删除成功',
          type: 'success',
          showClose: true,
          duration: 3000
        })
      }).catch(() => {

      })
    },
    async exportData() {
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 通过双重循环获取数据
      // header 从哪来? -> headers(中英文的对应关系自定义对象) Object.keys(headers) 获得
      // data 从哪来? -> 利用双重循环通过各种 key 获得数据

      // 获取所有数据,而不是某一页的某几个数据
      const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
      const data = this.formatJson(headers, rows)
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: Object.keys(headers), // 表头 必填
          data, // 具体数据 必填
          filename: '员工资料表', // 非必填
          // 复杂表头
          multiHeader,
          // 合并单元格
          merges
        })
      })
    },
    showQrCodedialog(url) {
      if (url) {
        this.qrCodedialogVisible = true
        // 上一步修改变量,控制弹框的渲染是异步操作
        this.$nextTick(() => {
          QRCode.toCanvas(this.$refs.myCanvas, url, function(error) {
            if (error) console.error(error)
            console.log('success!')
          })
        })
      } else {
        this.$message.warning('该用户还没有上传头像')
      }
    },
    formatJson(headers, rows) {
      return rows.map(item => {
        return Object.keys(headers).map(t => {
          // 格式化时间以及聘用形式
          if (['timeOfEntry', 'correctionTime'].includes(headers[t])) {
            // 方式1. 在js中使用过滤器
            // return Vue.filter('formatDate')(item[headers[t]])
            // 方式2. 直接使用方法
            return formatDate(item[headers[t]])
          } else if (headers[t] === 'formOfEmployment') {
            const count = EmployeesEnum.hireType.find(i => i.id === item[headers[t]])
            return count ? count.value : '未知'
          }
          return item[headers[t]]
        })
      })

      /* 笔记分解 */
      // headers = {'姓名': 'username','手机号': 'mobile',...}
      // rows = [{username:'zs',mobile: '123',...},...]
      // 目标results = [['zs','123']]
      // 方式1.2层循环,第1层,forEach循环数组rows
      // 第2层,通过for in 循环 header对象
      /*
      let results = []
      rows.forEach(item =>{
        let a = []
        for(var key in headers){
          //key = '姓名'
          //trueKey = 'username'
          let trueKey = headers[key]
          let value = item[trueKey]
          a.push(value)
        }
        results.push(a)
      })
       */
      // 方式2.1 用一个map
      /*
      let results = rows.map(item =>{
        let a = []
        for(var key in headers){
          //key = '姓名'
          //trueKey = 'username'
          let trueKey = headers[key]
          let value = item[trueKey]
          a.push(value)
        }
        return a
      })
      */
      // 方式2.2for in 循环对象通过Object.keys改为循环数组
      /*
      let results = rows.map(item =>{
        let a = []
        Object.keys(headers).forEach(key=>{
          //key = '姓名'
          //trueKey = 'username'
          let trueKey = headers[key]
          let value = item[trueKey]
          a.push(value)
        })
        return a
      })
      */
      //  方式2.3用第个map
      /*
      let results = rows.map(item =>{
        let a = Object.keys(headers).map(key=>{
          //key = '姓名'
          //trueKey = 'username'
          let trueKey = headers[key]
          let value = item[trueKey]
          return value
        })
        return a
      })
      */
      // 方式2.4 取消中间变量a value, trueKey
      /*
      let results = rows.map(item =>{
        return Object.keys(headers).map(key=>{
          //key = '姓名'
          //trueKey = 'username'
          return item[headers[key]]
        })
      })
      */
      // 方式2.5 取消return关键字,箭头函数只有一句话可以取消
      // return rows.map(item => Object.keys(headers).map(key => item[headers[key]]))
    },
    // 分配角色弹出层
    async onAssignRole(id) {
      this.userId = id
      // await this.$refs.assignRole.getUserInfo(id)
      this.showRoledialog = true
    }

  }
}
</script>

<style lang="less" scoped>
</style>
